package com.freeter.modules.gjs.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.freeter.modules.gjs.dto.ReCalcDataObj;
import com.freeter.modules.gjs.entity.*;
import com.freeter.modules.gjs.mapper.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Component
public class ReCalcCompoent {


    private static final Logger logger = LogManager.getLogger(ReCalcCompoent.class);
    private  final String  Gr_Action_Update="UPDATE";
    private  final String  Gr_Action_Add="ADD";
    private  final String  Gr_Action_Cancel="CANCEL";

    @Autowired
    private GrMapper grMapper;
    @Autowired private GrItemMapper grItemMapper;
    @Autowired private MstrSiteMapper mstrSiteMapper;
    @Autowired private MstrUomMapper mstrUomMapper;
    @Autowired private MstrItemsMapper mstrItemsMapper;
    @Autowired private StockStatusMapper stockStatusMapper;
    @Autowired private TransactionMapper transactionMapper;
    @Autowired private TransferRequestMapper transferRequestMapper;
    @Autowired private TransferItemsMapper transferItemsMapper;
    @Autowired private DamageReportMapper damageReportMapper;
    @Autowired private ObjectMapper objectMapper;
    @Autowired private AppRequestRecordMapper appRequestRecordMapper;
    @Autowired private MstrCat00Mapper mstrCat00Mapper;
    @Autowired private MstrCat01Mapper mstrCat01Mapper;
    @Autowired private MstrCat02Mapper mstrCat02Mapper;

    @Autowired private StockStatusTmpMapper stockStatusTmpMapper;
    @Autowired private TransactionTmpMapper transactionTmpMapper;
    @Autowired private TransactionUseDamgeAdjustMapper transactionUseDamgeAdjustMapper;


    public void doReCalcStock() {
        //开始循环处理，直到数据处理完毕
        int cnt = 0;
        int startRow = 0;
        while(true) {
            //获取要重新计算的gr,use, damage，Adjust
            cnt++;
            List<ReCalcDataObj> reCalcDataLst = getReCalcRecord(startRow);
            //startRow = (cnt-1 )*1000+1;
            if(reCalcDataLst == null || reCalcDataLst.size()<1){
                logger.info("本次重跑已完成");
                break;
            }
            for (ReCalcDataObj reCalcDataObj : reCalcDataLst) {
                try {
                    if ("GR".equals(reCalcDataObj.getSource())) {
                        grInstock(reCalcDataObj);
                    } else if ("Use".equals(reCalcDataObj.getSource())) {
                        usedInstock(reCalcDataObj);
                    } else if ("Adjust".equals(reCalcDataObj.getSource())) {
                        adjustInstock(reCalcDataObj);
                    } else if ("Damage".equals(reCalcDataObj.getSource())) {
                        damageInstock(reCalcDataObj);
                    }
                } catch (Exception e) {
                    logger.error("重算错误：{}", reCalcDataObj, e);
                    updateErrorFlag(reCalcDataObj);
                }

            }
        }
    }

    private void updateErrorFlag(ReCalcDataObj reCalcDataObj) {
        if ("GR".equals(reCalcDataObj.getSource())) {
            Gr tmpGr = new Gr();
            tmpGr.setId(reCalcDataObj.getId());
            tmpGr.setReCalcStatus(2);
            grMapper.updateById(tmpGr);
        } else if ("Use".equals(reCalcDataObj.getSource())) {
            logger.error("领用数据重算错误： transationId :{}", reCalcDataObj.getId());
            TransactionUseDamgeAdjust errObj = new TransactionUseDamgeAdjust();
            errObj.setId(reCalcDataObj.getId());
            errObj.setReCalcStatus(2);
            transactionUseDamgeAdjustMapper.updateById(errObj);
        } else if ("Adjust".equals(reCalcDataObj.getSource())) {
            logger.error("库存调整数据重算错误：transationId :{}", reCalcDataObj.getId());
            TransactionUseDamgeAdjust errObj = new TransactionUseDamgeAdjust();
            errObj.setId(reCalcDataObj.getId());
            errObj.setReCalcStatus(2);
            transactionUseDamgeAdjustMapper.updateById(errObj);
        } else if ("Damage".equals(reCalcDataObj.getSource())) {
            logger.error("报损数据重算错误：transationId :{}", reCalcDataObj.getId());
            TransactionUseDamgeAdjust errObj = new TransactionUseDamgeAdjust();
            errObj.setId(reCalcDataObj.getId());
            errObj.setReCalcStatus(2);
            transactionUseDamgeAdjustMapper.updateById(errObj);
        }
    }

    /**
     * 读取待重算的数据
     * @return
     */
    private List<ReCalcDataObj> getReCalcRecord(Integer startRow) {
        return this.grMapper.getReCalcRecord(startRow);
    }

    /**
     * 报损处理
     * @param reCalcDataObj
     */
    private void damageInstock(ReCalcDataObj reCalcDataObj) {
        TransactionUseDamgeAdjust transaction = this.transactionUseDamgeAdjustMapper.selectById(reCalcDataObj.getId());
        StockStatusTmp stockStatusTmp = this.getStockStatusTmpByTransation(transaction.getSiteId(),transaction.getItemBarcode(),transaction.getItemUomId());
        if(stockStatusTmp == null){
            logger.warn("报损的时候没有找到库存 transationId:{}", reCalcDataObj.getId());
            this.updateErrorFlag(reCalcDataObj);
            return;
        }
        BigDecimal stockQty = stockStatusTmp.getStockQty().subtract(transaction.getQty());
        this.updateStockById(stockStatusTmp.getId(),stockQty);
        TransactionTmp transactionTmp = new TransactionTmp();
        BeanUtils.copyProperties(transaction,transactionTmp);
        transactionTmp.setStockId(stockStatusTmp.getId());
        transactionTmp.setId(null);
        transactionTmp.setUponCalc(stockQty);
        transactionTmp.setRemarks("报损");
        transactionTmp.setReCalcStatus(1);
        transactionTmp.setUpdateRemarks("报损记录");
        this.transactionTmpMapper.insert(transactionTmp);
        //更新计算状态
        TransactionUseDamgeAdjust changeTransactionUseDamageAdjust = new TransactionUseDamgeAdjust();
        changeTransactionUseDamageAdjust.setId(transaction.getId());
        changeTransactionUseDamageAdjust.setReCalcStatus(1);
        this.transactionUseDamgeAdjustMapper.updateById(changeTransactionUseDamageAdjust);

    }


    /**
     * 库存调整处理
     * @param reCalcDataObj
     */
    private void adjustInstock(ReCalcDataObj reCalcDataObj) {
        TransactionUseDamgeAdjust transaction = this.transactionUseDamgeAdjustMapper.selectById(reCalcDataObj.getId());
        StockStatusTmp stockStatusTmp = this.getStockStatusTmpByTransation(transaction.getSiteId(),transaction.getItemBarcode(),transaction.getItemUomId());
        if(stockStatusTmp == null){
            logger.warn("库存调整的时候没有找到库存 transationId:{}", reCalcDataObj.getId());
            this.updateErrorFlag(reCalcDataObj);
            return;
        }
        //根据node js 源码 调整库存是在原库存上增加
        BigDecimal stockQty = stockStatusTmp.getStockQty().add(transaction.getQty());
        this.updateStockById(stockStatusTmp.getId(),stockQty);
        TransactionTmp transactionTmp = new TransactionTmp();
        BeanUtils.copyProperties(transaction,transactionTmp);
        transactionTmp.setStockId(stockStatusTmp.getId());
        transactionTmp.setId(null);
        transactionTmp.setUponCalc(stockQty);
        transactionTmp.setReCalcStatus(1);
        transactionTmp.setRemarks("调整库存记录");
        transactionTmp.setUpdateRemarks("调整库存记录");
        this.transactionTmpMapper.insert(transactionTmp);
        //更新计算状态
        TransactionUseDamgeAdjust changeTransactionUseDamageAdjust = new TransactionUseDamgeAdjust();
        changeTransactionUseDamageAdjust.setId(transaction.getId());
        changeTransactionUseDamageAdjust.setReCalcStatus(1);
        this.transactionUseDamgeAdjustMapper.updateById(changeTransactionUseDamageAdjust);
    }

    /**
     * 领用处理
     * @param reCalcDataObj
     */
    public void usedInstock(ReCalcDataObj reCalcDataObj ) {
        TransactionUseDamgeAdjust transaction = this.transactionUseDamgeAdjustMapper.selectById(reCalcDataObj.getId());
        StockStatusTmp stockStatusTmp = this.getStockStatusTmpByTransation(transaction.getSiteId(),transaction.getItemBarcode(),transaction.getItemUomId());
        if(stockStatusTmp == null){
            logger.warn("领用的时候没有找到库存 transationId:{}", reCalcDataObj.getId());
            this.updateErrorFlag(reCalcDataObj);
            return;
        }
        BigDecimal stockQty = stockStatusTmp.getStockQty().subtract(transaction.getQty());
        this.updateStockById(stockStatusTmp.getId(),stockQty);
        TransactionTmp transactionTmp = new TransactionTmp();
        BeanUtils.copyProperties(transaction,transactionTmp);
        transactionTmp.setStockId(stockStatusTmp.getId());
        transactionTmp.setId(null);
        transactionTmp.setUponCalc(stockQty);
        transactionTmp.setRemarks("领用");
        transactionTmp.setUpdateRemarks("领用记录");
        transactionTmp.setReCalcStatus(1);
        this.transactionTmpMapper.insert(transactionTmp);

        //更新计算状态
        TransactionUseDamgeAdjust changeTransactionUseDamageAdjust = new TransactionUseDamgeAdjust();
        changeTransactionUseDamageAdjust.setId(transaction.getId());
        changeTransactionUseDamageAdjust.setReCalcStatus(1);
        this.transactionUseDamgeAdjustMapper.updateById(changeTransactionUseDamageAdjust);
    }

    private void updateStockById(Long stockId,BigDecimal qty){
        StockStatusTmp stockStatusTmp = new StockStatusTmp();
        stockStatusTmp.setId(stockId);
        stockStatusTmp.setStockQty(qty);
        this.stockStatusTmpMapper.updateById(stockStatusTmp);
    }

    private StockStatusTmp getStockStatusTmpByTransation(Long siteId,String itemBarcode,Long uomId){
        StockStatusTmp stockQuery = new StockStatusTmp();
        stockQuery.setSiteId(siteId);
        stockQuery.setItemUomId(uomId);
        stockQuery.setItemBarcode(itemBarcode);
        return this.stockStatusTmpMapper.selectOne(stockQuery);
    }


    /**
     * gr 入库
     * @param reCalcDataObj
     */
    public void grInstock(ReCalcDataObj reCalcDataObj) {
        // 解析GR主表和明细
        Gr gr = grMapper.selectById(reCalcDataObj.getId());
        setSite(gr);
        processGrItem(gr);
        updateGrProcessStatus(gr);

    }

    private Gr getPrevGr(Gr gr) {
        if (gr == null || gr.getRefno() == null || gr.getProjectno() == null || gr.getRecordTime() == null) {
            return null;
        }
        Wrapper<Gr> wrapper = new EntityWrapper<>();
        wrapper.eq("refno", gr.getRefno())
                .eq("projectno", gr.getProjectno())
                .lt("record_time", gr.getRecordTime())
                .orderBy("record_time", false)
                .last("limit 1");
        List<Gr> list = grMapper.selectList(wrapper);
        return (list != null && !list.isEmpty()) ? list.get(0) : null;
    }

    private void processGrItem(Gr gr) {
        //冲销库存
        chongxiaoStock(gr);

        //如果是cancel 冲销完后不做后续库存和库存记录的处理
        if (gr.getAction().equals(Gr_Action_Cancel)) {
            return;
        }
        // 如果是update 冲销完后，记录update gr的明细， 如果是add 处理库存增加和库存记录
        updateStockAndInsertTransation(gr);
    }

    private void updateStockAndInsertTransation(Gr gr) {
        Wrapper<GrItem> queryItem = new EntityWrapper<>();
        queryItem.eq("gr_id", gr.getId());
        List<GrItem> items = grItemMapper.selectList(queryItem);
        //逐个item处理
        for (GrItem item : items) {
            //补全明细相关主数据
            setItemUomIdAndMstrItem(item);
            //查找库存是否存在
            StockStatusTmp stockStatusTmp = addStock(gr,item);
            // 流水处理逻辑
            grTransactionProcess(gr,item,stockStatusTmp);
        }
    }

    /**
     * 冲销库存和记录冲销库存变动记录
     * @param gr
     */
    private void chongxiaoStock(Gr gr) {
        if (!gr.getAction().equals(Gr_Action_Update) && !gr.getAction().equals(Gr_Action_Cancel)) {
            return;
        }
        Gr oldGr  = getPrevGr(gr);
        if(oldGr == null){
            return;
        }

        Wrapper<GrItem> queryOldItem = new EntityWrapper<>();
        queryOldItem.eq("gr_id", oldGr.getId());
        List<GrItem> oldGrItems = grItemMapper.selectList(queryOldItem);
        if(oldGrItems == null && oldGrItems.size()<1){
            return;
        }
        //projectNo 转site_id
        setSite(oldGr);

        for (GrItem oldItem : oldGrItems) {
            //补全明细相关主数据
            setItemUomIdAndMstrItem(oldItem);
            StockStatusTmp oldExist = getStockStatusTmp(oldItem, oldGr);
            if(oldExist ==null){
                logger.error("重新库存报错 gr_id:{}", gr.getId());
            }
            if (oldExist != null) {
                StockStatusTmp tmp = new StockStatusTmp();
                tmp.setId(oldExist.getId());
                tmp.setStockQty(oldExist.getStockQty().subtract(oldItem.getQty()));
                tmp.setLastUpdate(gr.getRecordTime());
                stockStatusTmpMapper.updateById(tmp);

                //记录冲销记录
                insertTransation(oldItem, oldExist, tmp, oldGr, gr);
            }
        }
    }

    private void insertTransation(GrItem oldItem, StockStatusTmp oldExist, StockStatusTmp tmp, Gr oldGr,Gr gr) {
        TransactionTmp trx = new TransactionTmp();
        trx.setStockId(oldExist.getId());
        trx.setQty(oldItem.getQty().negate()); // 负数
        trx.setRemarks(gr.getPrno()+"抵销"+oldGr.getPrno());
        trx.setUponCalc(tmp.getStockQty());
        trx.setNewBalanceQty(tmp.getStockQty());
        trx.setUpdateRemarks(gr.getPrno()+"抵销"+oldGr.getPrno());
        trx.setReCalcStatus(1);
        trx.setIsDeleted(0);
        trx.setCalcStatus(1);
        trx.setSource("GR");
        trx.setRecordTime(new Date());
        trx.setRefNo(oldGr.getRefno());
        trx.setPoNo(oldGr.getPono());
        trx.setPrNo(oldGr.getPrno());
        trx.setScForm(oldItem.getScform());
        trx.setDnDirName(oldGr.getDnDirName());
        trx.setTmmUrl(oldGr.getUrl());
        trx.setRecvSiteId(oldGr.getRecvSiteId());
        trx.setGrId(oldGr.getId());
        trx.setGrItemId(oldItem.getId());
        trx.setIsTransfer(0);
        trx.setRecordTime(gr.getRecordTime());
        transactionTmpMapper.insert(trx);
    }

    private StockStatusTmp getStockStatusTmp(GrItem oldItem, Gr oldGr) {
        StockStatusTmp stockQuery = new StockStatusTmp();
        stockQuery.setSiteId(oldGr.getRecvSiteId());
        stockQuery.setItemUomId(oldItem.getUomId());
        stockQuery.setItemBarcode(oldItem.getItemBarcode());
        return  stockStatusTmpMapper.selectOne(stockQuery);
    }

    private void updateGrProcessStatus(Gr gr) {
        // 更新GR主表，reCalcStatus=1
        Gr updateTmpGr  = new Gr();
        updateTmpGr.setId(gr.getId());
        updateTmpGr.setReCalcStatus(1);
        grMapper.updateById(updateTmpGr);
    }

    private void setItemUomIdAndMstrItem(GrItem item) {
        // 校验/补全UOM
        MstrUom uomQuery = new MstrUom();
        uomQuery.setDescEn(item.getUom() );
        uomQuery.setIsDeleted(0);
        MstrUom uom = mstrUomMapper.selectOne(uomQuery);
        if (uom == null) {
            uom = new MstrUom();
            uom.setDescEn(item.getUom());
            mstrUomMapper.insert(uom);
        }
        item.setUomId(uom.getId());
        // 校验/补全物品
        Wrapper<MstrItems> mstrItemQuery = new EntityWrapper<>();
        mstrItemQuery.eq("item_desc",item.getItemdesc());
        mstrItemQuery.eq("is_deleted",0);
        mstrItemQuery.eq("uom_id",uom.getId());
        List<MstrItems> mstrItemLst = mstrItemsMapper.selectList(mstrItemQuery);
        if(mstrItemLst == null || mstrItemLst.size()<0){
            MstrItems mstrItem = new MstrItems();
            String catId = getCatId(item.getProdcat());
            mstrItem.setCatId(catId);
            mstrItem.setItemBarcode(UUID.randomUUID().toString());
            mstrItem.setUomId(uom.getId());
            mstrItem.setItemDesc(item.getItemdesc());
            mstrItem.setIsExpansive(0);
            mstrItem.setCheckExpiry(0);
            mstrItem.setCreatedt(new Date());
            mstrItem.setIsDeleted(0);
            mstrItemsMapper.insert(mstrItem);
            item.setItemBarcode(mstrItem.getItemBarcode());
            return;
        }

        item.setItemBarcode(mstrItemLst.get(0).getItemBarcode());
    }

    private void setSite(Gr gr) {
        // 主数据校验/补全
        // 1. 校验/补全站点
        MstrSite site = mstrSiteMapper.selectOne(new MstrSite() {{ setProjectCode(gr.getProjectno()); setIsDeleted(0); }});
        if (site == null) {
            site = new MstrSite();
            site.setProjectCode(gr.getProjectno());
            site.setIsDeleted(0);
            mstrSiteMapper.insert(site);
        }
        gr.setRecvSiteId(site.getId());
    }

    /**
     * 根据prodCat 转换成catId
     * @param prodCat
     * @return
     */
    private String getCatId(String prodCat) {
        if (prodCat == null || prodCat.length() < 12) {
            return prodCat;
        }
        String cat00Code = prodCat.substring(0, 4);
        String cat01Code = prodCat.substring(4, 8);
        String cat02Code = prodCat.substring(8, 12);

        // 1. 处理第一级 mstr_cat_00
        MstrCat00 cat00 = mstrCat00Mapper.selectById(cat00Code);
        if (cat00 == null) {
            mstrCat00Mapper.insertWithCustomId(Long.valueOf(cat00Code),cat00Code,0);
        }
        // 2. 处理第二级 mstr_cat_01
        Wrapper<MstrCat01> cat01Query = new EntityWrapper<>();
        cat01Query.eq("id", cat01Code).eq("plevel", Long.valueOf(cat00Code)).eq("is_deleted",0);
        List<MstrCat01> cat01List = mstrCat01Mapper.selectList(cat01Query);
        MstrCat01 cat01 = (cat01List != null && !cat01List.isEmpty()) ? cat01List.get(0) : null;
        if (cat01 == null) {
            mstrCat01Mapper.insertWithCustomId(Long.valueOf(cat01Code),cat01Code,cat01Code,Long.valueOf(cat00Code),0);
        }
        // 3. 处理第三级 mstr_cat_02
        com.baomidou.mybatisplus.mapper.EntityWrapper<MstrCat02> cat02Query = new com.baomidou.mybatisplus.mapper.EntityWrapper<>();
        cat02Query.eq("id", cat02Code).eq("plevel", cat01Code).eq("is_deleted",0);;
        List<MstrCat02> cat02List = mstrCat02Mapper.selectList(cat02Query);
        MstrCat02 cat02 = (cat02List != null && !cat02List.isEmpty()) ? cat02List.get(0) : null;
        if (cat02 == null) {
            mstrCat02Mapper.insertWithCustomId(Long.valueOf(cat02Code),cat02Code,Long.valueOf(cat01Code),0);
        }
        // 最终cat_id仍然用prodCat（12位字符串），不变
        return prodCat;
    }

    /**
     * 查找或插入库存状态（StockStatusTmp）
     * @param gr GR主表
     * @param item GR明细
     * @return StockStatusTmp
     */
    private StockStatusTmp addStock(Gr gr, GrItem item) {
        // 4. 查找库存状态
        StockStatusTmp exist = getStockStatusTmp(item, gr);
        //更新库存
        if (exist != null) {
            return updateStock(item, exist, gr);
        }
        // 5. 不存在则插入

        StockStatusTmp stock = new StockStatusTmp();
        stock.setSiteId(gr.getRecvSiteId());
        stock.setProjectNo(gr.getProjectno());
        stock.setItemCatId(item.getProdcat());
        stock.setItemBarcode(item.getItemBarcode());
        stock.setItemDesc(item.getItemdesc());
        stock.setItemUomId(item.getUomId());
        stock.setStockQty(item.getQty());
        stock.setHoldQty(java.math.BigDecimal.ZERO);
        stock.setRecordDate(gr.getRecordTime());
        stock.setLastGr(gr.getRecordTime());
        stock.setLastUpdate(gr.getRecordTime());
        stockStatusTmpMapper.insert(stock);
        return stock;
    }

    private StockStatusTmp updateStock(GrItem item, StockStatusTmp exist,Gr gr) {
        StockStatusTmp tmp = new StockStatusTmp();
        tmp.setId(exist.getId());
        tmp.setStockQty(item.getQty().add(exist.getStockQty()));
        tmp.setLastGr(gr.getRecordTime());
        tmp.setLastUpdate(gr.getRecordTime());
        stockStatusTmpMapper.updateById(tmp);
        return tmp;
    }

    /**
     * 1. 查询是否存在
     *    存在：
     *       1. 判断是否被删除， 如果被删除，添加到记录更新信息  delete flag change
     *       2. 计算new_balance_qty ,并且判断是否跟upon_qty, 如果不一样添加修改信息： balance change
     *       gr的时间跟transation时间对比
     *    不存在：新增
     *       1. 创建 Transaction
     *       2. 设置calc_status = 1,
     *       3. 设置其他信息
     *       4. 计算upon_qty, new_balance_qty , update_remarks： insert
     */
    private void grTransactionProcess(Gr gr, GrItem item,StockStatusTmp stockStatusTmp) {

        /**
         * gr=>stock 字段对应关系
         *  //根据物料 item_barcode、站点、单位id查询库存状态，如果存在则更新库存数量，否则插入新库存状态
         *                   let stock_status_list = await trx('view_stock_status').distinct('id')
         *                     .where('site_id', '=', mstr_site.id).andWhere('item_uom_id', '=', mstr_uom.id)
         *                     .andWhere('item_barcode', '=', mstr_item.item_barcode);
         *  site_id: mstr_site.id,
         *  item_cat_id: mstr_item.cat_id,
         *  item_barcode: mstr_item.item_barcode,
         *  item_desc: mstr_item.item_desc,
         *  item_uom_id: mstr_item.uom_id,
         *  stock_qty: item.Qty,
         *  last_gr: datetimenow,
         *  record_date: datetimenow
         *
         * gr=>transation 新增字段对应关系
         * stock_id: stock_id,          ==》跟item关联
         *                     supp_name: gr.SuppNam,
         *                     ref_no: gr.RefNo,===》跟gr关联
         *                     po_no: gr.PoNo,
         *                     pr_no: gr.PrNo,
         *                     sc_form: item.ScForm,
         *                     qty: item.Qty,
         *                     remarks: gr.Remarks,
         *                     upon_calc:  item.Qty ,
         *                     calc_status:  1 ,
         *                     dn_dir_name: gr.dn_dir_name,
         *                     tmm_url: gr.url,
         *                     is_transfer: 0,
         *                     recv_site_id: mstr_site.id,
         *                     source: 'GR',
         *                     record_time: datetimenow
         */
        TransactionTmp trx = new TransactionTmp();
        trx.setStockId(stockStatusTmp.getId());
        trx.setQty(item.getQty());
        trx.setRemarks("GR入库");
        trx.setUponCalc(stockStatusTmp.getStockQty());
        trx.setNewBalanceQty(item.getQty());
        trx.setUpdateRemarks("GR入库");
        trx.setReCalcStatus(1);
        trx.setIsDeleted(0);
        trx.setCalcStatus(1);
        trx.setSource("GR");
        trx.setRefNo(gr.getRefno());
        trx.setPoNo(gr.getPono());
        trx.setPrNo(gr.getPrno());
        trx.setScForm(item.getScform());
        trx.setDnDirName(gr.getDnDirName());
        trx.setTmmUrl(gr.getUrl());
        trx.setRecvSiteId(gr.getRecvSiteId());
        trx.setGrId(gr.getId());
        trx.setGrItemId(item.getId());
        trx.setIsTransfer(0);
        trx.setRecordTime(gr.getRecordTime());
        transactionTmpMapper.insert(trx);
    }
}
